using System;
using LogSystem;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;
using Yoozoo.Gameplay.Liberty.Pool;

namespace Yoozoo.Gameplay.Liberty.PlayerController
{
    /// <summary>
    /// 玩家锁定敌人辅助类 （仅供玩家使用！！！）
    /// </summary>
    public class PlayerLockTargetHelper : MonoBehaviour
    {
        [SerializeField]
        private float _FarDistance = 30;
        
        // 更新锁定的时间
        [SerializeField]
        private float _UpdateDuration = 0.1f;
        private float _Timer = 0f;

        // 主角AIEntity
        private AIEntity _playerEntity = null;
        
        // 当前锁定的敌人
        private AIEntity _currentLockTarget;
        // 当前索敌特效ID
        private int _currentLockTargetResID = 0;
        // 当前锁定敌人用的特效
        private Transform _currentLockTargetEffect;
        // 当前锁定敌人用的特效上的LockPointAnimation组件
        private LockPointAnimation _currentLockPointAnimation;
        
        // 是否正在使用自由瞄准 (远程武器使用)
        public bool UseFreeAim => _useFreeAim;
        private bool _useFreeAim = false;
        
        // 是否开启自由瞄准
        public bool FreeAimOpen = true;
        
        // 是否可显示锁定目标
        public bool CanShowLockTarget = true;

        public void InitData(AIEntity aiEntity)
        {
            _playerEntity = aiEntity;
        }

        /// <summary>
        /// 刷新锁定敌人/瞄准特效
        /// </summary>
        public void RefreshCurrentLockTarget()
        {
            if (_playerEntity==null || _playerEntity.battleAgent==null)
            {
                return;
            }

            _Timer = 0;


            BattleAgent playerBattleAgent = _playerEntity.battleAgent;
            // // 重新搜索锁定的敌人
            // playerBattleAgent.PlayerSearchLockTarget();
            // 根据当前武器，获取锁定特效资源ID
            int effectResID = GetLockTargetEffectResID();
            // 是否是远程瞄准特效
            bool isAimLockPointEffect = GetIsAimLockPointEffect();
            
            AIEntity targetAIEntity = playerBattleAgent.currentLockTarget;
            if (targetAIEntity == _currentLockTarget && effectResID == _currentLockTargetResID && (isAimLockPointEffect && _useFreeAim))
            {
                // 目标没改变，并且没有切换武器
                return;
            }
            
            // 新目标
            _currentLockTarget = targetAIEntity;
            _useFreeAim = false;
            if (isAimLockPointEffect && FreeAimOpen)
            {
                // 强制开启自由瞄准
                _useFreeAim = true;
            }
            // else if (targetAIEntity != null)
            // {
            //     // 有目标
            //     Transform lockTargetEffect = GetLockTargetEffect(effectResID);
            //
            //     Transform upperChestBone = targetAIEntity.viewer.animator.GetBoneTransform(HumanBodyBones.UpperChest);
            //     if (upperChestBone)
            //     {
            //         lockTargetEffect.SetParent(upperChestBone);
            //         lockTargetEffect.localPosition = Vector3.zero;
            //     }
            //     else
            //     {
            //         // Debug.LogError(LogModule.LibertySceneBattle, $"模型 {targetAIEntity.viewer.transform.name} 未找到UpperChest骨骼节点");
            //         lockTargetEffect.SetParent(targetAIEntity.viewer.transform);
            //         lockTargetEffect.localPosition = new Vector3(0, targetAIEntity.characterController.height*0.7f, 0);
            //     }
            //     lockTargetEffect.localRotation = Quaternion.identity;
            // }
            else if (isAimLockPointEffect)
            {
                // 无目标，自由瞄准
                _useFreeAim = true;
            }
            else
            {
                // 移除上一个目标的锁定特效
                RecycleLockTargetEffect();
            }
            
            // 设置准星是否可见
            SetLockTargetVisible(CanShowLockTarget);
        }

        /// <summary>
        /// 播放锁定敌人特效的攻击动画
        /// </summary>
        public void PlayLockTargetEffectAttackAnimation(bool hitTarget, bool killTarget)
        {
            if (_currentLockPointAnimation)
            {
                _currentLockPointAnimation.PlayAttackAnimation(hitTarget, killTarget);
            }
        }

        /// <summary>
        /// 获取当前准星物体
        /// </summary>
        /// <returns></returns>
        public Transform GetCurrentLockTargetEffect()
        {
            return _currentLockTargetEffect;
        }
        
        /// <summary>
        /// 是否是远程瞄准特效
        /// </summary>
        /// <returns></returns>
        bool GetIsAimLockPointEffect()
        {
            return (_playerEntity.data.aimingState!=AimingState.None || (_playerEntity.data.battleState!=BattleState.None && LibertyAIUtils.PlayerController.inputCamera.ControlMode==CameraControlMode.Input))
                   && (LibertyAIUtils.PlayerController.vehicleBehaviourMgr.enterExitCarState == EnterExitCarState.None);
        }

        // 根据当前武器，获取锁定特效资源ID
        int GetLockTargetEffectResID()
        {
            int effectResID = 0;
            if (_playerEntity.WeaponSystem.HandleWeapon!= null)
            {
                effectResID = _playerEntity.WeaponSystem.HandleWeapon.Config.reticle_type;
            }
            return effectResID;
        }

        // 获取瞄准特效
        Transform GetLockTargetEffect(int resID)
        {
            if (_currentLockTargetResID == resID && _currentLockTargetEffect)
            {
                RefreshAimTarget();
                return _currentLockTargetEffect;
            }

            // 回收上个锁定目标特效
            RecycleLockTargetEffect();
            
            // 新特效
            if (resID > 0)
            {
                _currentLockTargetResID = resID;
                _currentLockTargetEffect = LibertyPoolMgr.GetInstance().GetEffectObject(resID);
                _currentLockTargetEffect.gameObject.SetActive(true);
                _currentLockPointAnimation = _currentLockTargetEffect.GetComponent<LockPointAnimation>();
            
                // 设置IK瞄准目标
                // // LookAtIK
                // switch (_playerEntity.data.aimingState)
                // {
                //     case AimingState.NormalAim:
                //     case AimingState.ReloadAim:
                //         {
                //             // LookAtIK
                //             _playerEntity.viewer.animationAgent.SetLookAtTarget(IKAgent.LookAtType.Aim, _currentLockTargetEffect);
                //             _playerEntity.viewer.animationAgent.LookAtIKFadeIn();
                //         }
                //         break;
                // }
                // AimIK
                RefreshAimTarget(true);
            }
            
            return _currentLockTargetEffect;
        }

        // 刷新IK瞄准目标
        void RefreshAimTarget(bool firstRefresh = false)
        {
            // 设置IK瞄准目标
            switch (_playerEntity.data.aimingState)
            {
                case AimingState.NormalAim:
                case AimingState.ReloadAim:
                    {
                        // AimIK
                        _playerEntity.viewer.animationAgent.SetAimTarget(WeaponIKType.HandGunAimIK, _currentLockTargetEffect);
                    }
                    break;
            }
        }

        // 设置准星是否可见 （用于换弹时，隐藏准星，但不回收准星GameObject）
        void SetLockTargetVisible(bool isVisible)
        {
            if (_currentLockTargetResID != 0)
            {
                if (_currentLockPointAnimation)
                {
                    _currentLockPointAnimation.SetVisible(isVisible);
                }
            }
        }

        // 回收锁定目标特效
        void RecycleLockTargetEffect()
        {
            if (_currentLockTargetResID != 0)
            {
                if (_currentLockTargetEffect)
                {
                    LibertyPoolMgr.GetInstance().RecycleEffect(_currentLockTargetResID, _currentLockTargetEffect);
                    _currentLockTargetEffect = null;
                    _currentLockPointAnimation = null;
                    
                    // 清理IK瞄准目标
                    if (_playerEntity.data.aimingState != AimingState.None)
                    {
                        // // LookAtIK
                        // _playerEntity.viewer.animationAgent.ClearLookAtTarget();
                        // _playerEntity.viewer.animationAgent.LookAtIKFadeOut();
                        // AimIK
                        _playerEntity.viewer.animationAgent.SetAimTarget(WeaponIKType.HandGunAimIK, null);  // TODO: 当前写死了瞄准类型为手枪
                    }
                }
                _currentLockTargetResID = 0;
            }
        }
        
        // 刷新自由瞄准特效位置
        void RefreshFreeAimLockTargetEffect()
        {
            // 是否是远程瞄准特效
            bool isAimLockPointEffect = GetIsAimLockPointEffect();
            if (!isAimLockPointEffect)
            {
                // 当前处于非瞄准状态，回收并取消刷新
                RecycleLockTargetEffect();
                _useFreeAim = false;
                return;
            }
            
            int effectResID = GetLockTargetEffectResID();
            Transform lockTargetEffect = GetLockTargetEffect(effectResID);
            if (lockTargetEffect)
            {
                // 直接挂在对象池节点上
                lockTargetEffect.parent = LibertyPoolMgr.GetInstance().EffectRoot;
   
                // 注意：这里使用inputCamera的虚拟相机位置信息，不要直接拿cinemachineBrain的，执行顺序错误会造成准星抖动
                Vector3 position = LibertyAIUtils.PlayerController.cameraController.inputVirtualCamera.transform.localToWorldMatrix.MultiplyPoint(new Vector3(0, 0, _FarDistance));
                lockTargetEffect.position = position;
                lockTargetEffect.localRotation = Quaternion.identity;
            }

            SetLockTargetVisible(CanShowLockTarget);
        }

        void Update()
        {
            _Timer += Time.deltaTime;
            if (_Timer >= _UpdateDuration)
            {
                RefreshCurrentLockTarget();
            }
            
        }

        void LateUpdate()
        {
            if (_useFreeAim)
            {
                RefreshFreeAimLockTargetEffect();
            }
        }
        
    }
}
